package com.nlp.mallet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;

import cc.mallet.classify.Classifier;
import cc.mallet.classify.ClassifierTrainer;
import cc.mallet.classify.MaxEntTrainer;
import cc.mallet.classify.Trial;
import cc.mallet.pipe.iterator.CsvIterator;
import cc.mallet.types.Alphabet;
import cc.mallet.types.FeatureVector;
import cc.mallet.types.Instance;
import cc.mallet.types.InstanceList;
import cc.mallet.types.Label;
import cc.mallet.types.LabelAlphabet;
import cc.mallet.types.Labeling;
import cc.mallet.util.Randoms;

public class Maxent implements Serializable{
    
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * 训练分类器
	 * @param trainingInstances
	 * @return
	 */
    public Classifier trainClassifier(InstanceList trainingInstances) {
        // 这里我们使用最大熵（即多分类逻辑回归）分类器。.                                                 
        ClassifierTrainer<?> trainer = new MaxEntTrainer();
        return trainer.train(trainingInstances);
    }
    
    /**
     * 保存经过训练的分类器/将训练好的分类器写入磁盘
     * @param classifier
     * @param savePath
     * @throws IOException
     */
    public void saveClassifier(Classifier classifier,String savePath) throws IOException{
        ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(savePath));
        oos.writeObject(classifier);
        oos.flush();
        oos.close();        
    }
    
    /**
     * 恢复保存的分类器
     * @param savedPath
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     * @throws ClassNotFoundException
     */
    public Classifier loadClassifier(String savedPath) throws FileNotFoundException, IOException, ClassNotFoundException{                                              
        //这里，我们从文件加载一个序列化的分类器 
    	Classifier classifier;
        ObjectInputStream ois = new ObjectInputStream (new FileInputStream (new File(savedPath)));
        classifier = (Classifier) ois.readObject();
        ois.close();
        return classifier;
    }
    
    /**
     * 预测与评价
     */
    public String predict(Classifier classifier,Instance testInstance){
        Labeling labeling = classifier.classify(testInstance).getLabeling();
        Label label = labeling.getBestLabel();
        return (String)label.getEntry();
    }
    
    public void evaluate(Classifier classifier, String testFilePath) throws IOException {
        InstanceList testInstances = new InstanceList(classifier.getInstancePipe());                                                                                                                                                                
        
        //输入数据的格式 :[name] [label] [data ... ]                                                                    
        CsvIterator reader = new CsvIterator(new FileReader(new File(testFilePath)),"(\\w+)\\s+(\\w+)\\s+(.*)",3, 2, 1);  // (data, label, name) field indices               

        // 将迭代器加载的所有实例添加到实例列表中
        testInstances.addThruPipe(reader);
        Trial trial = new Trial(classifier, testInstances);

        //评估度量、精度、召回和F1
        System.out.println("Accuracy: " + trial.getAccuracy());                                                      
        System.out.println("F1 for class 'good': " + trial.getF1("good"));
        System.out.println("Precision for class '" +
                           classifier.getLabelAlphabet().lookupLabel(1) + "': " +
                           trial.getPrecision(1));
    }

    /**
     * 执行n次交叉验证
     * @param trainer
     * @param instances
     * @return
     */
     public Trial testTrainSplit(MaxEntTrainer trainer, InstanceList instances) {
         int TRAINING = 0;
         int TESTING = 1;
         int VALIDATION = 2;
     
         // 将输入列表分成训练（90%）和测试（10%）列表。
         InstanceList[] instanceLists = instances.split(new Randoms(), new double[] {0.9, 0.1, 0.0});
         Classifier classifier = trainClassifier(instanceLists[TRAINING]);
         return new Trial(classifier, instanceLists[TESTING]);
      }
     
    public static void main(String[] args) throws FileNotFoundException,IOException{
        //定义训练样本
        Alphabet featureAlphabet = new Alphabet();//特征词典
        LabelAlphabet targetAlphabet = new LabelAlphabet();//类标词典   实例目标的词汇表
        targetAlphabet.lookupIndex("positive");
        targetAlphabet.lookupIndex("negative");
        targetAlphabet.lookupIndex("neutral");
        targetAlphabet.stopGrowth();
        featureAlphabet.lookupIndex("f1");
        featureAlphabet.lookupIndex("f2");
        featureAlphabet.lookupIndex("f3");
        //训练样本
        InstanceList trainingInstances = new InstanceList (featureAlphabet,targetAlphabet);//实例集对象
        final int size = targetAlphabet.size();
         
        double[] featureValues1 = {1.0, 0.0, 0.0};
        double[] featureValues2 = {2.0, 0.0, 0.0};
        double[] featureValues3 = {0.0, 1.0, 0.0};
        double[] featureValues4 = {0.0, 0.0, 1.0};
        double[] featureValues5 = {0.0, 0.0, 3.0};
        
        
       
        String[] targetValue = {"positive","positive","neutral","negative","negative"};
        List<double[]> featureValues = Arrays.asList(featureValues1,featureValues2,featureValues3,featureValues4,featureValues5); 
        int i = 0;
        for(double[]featureValue:featureValues){
            FeatureVector featureVector = new FeatureVector(featureAlphabet,
                    (String[])targetAlphabet.toArray(new String[size]),featureValue);//将列表更改为数组
            Instance instance = new Instance (featureVector,targetAlphabet.lookupLabel(targetValue[i]), "f1",null);
            i++;
            trainingInstances.add(instance);
        }
        Maxent maxent = new Maxent();
        Classifier trainClassifier = maxent.trainClassifier(trainingInstances);
        Classifier maxentclassifier = maxent.trainClassifier(trainingInstances);
        //加载测试实例
        double[] testfeatureValues = {0.5, 0.5, 6.0};
        FeatureVector testfeatureVector = new FeatureVector(featureAlphabet,
                (String[])targetAlphabet.toArray(new String[size]),testfeatureValues);
        //创建 实例（数据、目标、名称、源） 测试样本
        Instance testinstance = new Instance (testfeatureVector,targetAlphabet.lookupLabel("positive"), "f3wweweew",null);
        System.out.print(maxent.predict(maxentclassifier, testinstance));
        //maxent.evaluate(maxentclassifier, "resource/testdata.txt");
    }
}